<template>
  <div class="app-container layout-container">
    <a-breadcrumb>
      <a-breadcrumb-item>租户权限</a-breadcrumb-item>
      <a-breadcrumb-item>菜单配置</a-breadcrumb-item>
      <a-breadcrumb-item>系统设置</a-breadcrumb-item>
    </a-breadcrumb>
    <div class="org-container">
      <!--    部门树 start  -->
      <div class="app-container org-container-tree">
        <div class="org-tree-header">
          <div class="title">
            <span class="circle"></span>
            <span class="title-label">组织架构</span>
          </div>
          <div class="async-btn" v-show="false">
            <GiSvgIcon name="async" size="16" />
            <span>同步钉钉</span>
          </div>
        </div>
        <div class="tree-box">
          <a-input-search
            placeholder="请输入关键词"
            v-model="deptName"
            :allow-clear="true"
            @search="handelDeptSearch"
            @clear="getDeptTree"
            @press-enter="handelDeptSearch"

          />
          <a-tree blockNode @select="handelTreeList" :data="deptTreeData" :fieldNames="treeFieldNames">
            <template #extra="nodeData">
              <GiSvgIcon name="org-edit" size="16" @click="handelEdit(nodeData)"></GiSvgIcon>
              <GiSvgIcon
                name="org-del"
                size="16"
                style="margin-left: 8px"
                @click="handelDel(nodeData)"
                v-if="nodeData.parentId != 0"
              ></GiSvgIcon>
            </template>
          </a-tree>
        </div>
        <div class="add-button">
          <a-button type="primary" @click="handleOpenAddEditOrg">
            <template #icon>
              <icon-plus />
            </template>
            新建组织
          </a-button>
        </div>
      </div>
      <!--    部门树 end  -->

      <!--   账号列表 start   -->
      <div class="app-container org-container-list">
        <div class="org-list-opt">
          <a-space>
            <a-button type="primary" @click="handelAddAccount">
              <template #icon>
                <icon-plus />
              </template>
              新建
            </a-button>
            <a-button type="outline" @click="handleUpTemplate">导入</a-button>
            <a-button @click="handelBatchDel">
              <template #icon>
                <icon-delete />
              </template>
              删除
            </a-button>
          </a-space>
          <a-input-search
            style="width: 246px"
            placeholder="请输入关键词"
            v-model="listParams.name"
            :allow-clear="true"
            @search="handelAccountSearch"
            @clear="getAccountList"
            @press-enter="handelAccountSearch"
          />
        </div>
        <a-table
          :data="accountList"
          :pagination="false"
          :stripe="true"
          :scroll="{ y: '100%' }"
          v-model:selectedKeys="selectedUserKeys"
          row-key="userId"
          :row-selection="rowSelection"
        >
          <template #columns>
            <a-table-column title="序号" :width="64">
              <template #cell="cell">{{ cell.rowIndex + 1 }}</template>
            </a-table-column>
            <a-table-column title="员工姓名" :width="100" tooltip ellipsis data-index="nickName"></a-table-column>
            <a-table-column
             title="部门" :width="160" data-index="mainDeptName"></a-table-column>
            <a-table-column title="手机号码"
              :sortable="{ sortDirections: ['ascend', 'descend'] }"
              :width="160"
              data-index="mobile"
            ></a-table-column>
            <a-table-column
              title="角色"
              :sortable="{ sortDirections: ['ascend', 'descend'] }"
              :width="150"
              tooltip
              ellipsis
              data-index="description"
            >
              <template #cell="{ record }">
                <span>{{ userRole(record.roles) || "/" }}</span>
              </template>
            </a-table-column>
            <a-table-column title="禁用/启用" :width="100">
              <template #cell="{ record }">
                <a-switch :loading="record.loading" :model-value="record.status" @change="handelAccountStatus(record)" />
              </template>
            </a-table-column>
            <a-table-column title="操作" :width="200" align="center">
              <template #cell="{ record }">
                <a-button type="text" class="user-list_btn" @click="handelEditAccount(record)">编辑</a-button>
                <!--                 <a-button type="text" class="user-list_btn" @click="handelAccount(record)">删除</a-button>-->
                <a-button type="text" class="user-list_btn" @click="handelDeptSet(record)">部门设置</a-button>
                <a-button type="text" class="user-list_btn" @click="handelResetPassword(record)">重置密码</a-button>
              </template>
            </a-table-column>
          </template>
        </a-table>
        <a-pagination
          :total="paginationTotal"
          v-model:current="listParams.current"
          v-model:pageSize="listParams.size"
          @change="handleChangePagination"
          @page-size-change="handleChangeSizePagination"
          :page-size-options="[15, 20, 30, 40]"
          show-total
          show-jumper
          show-page-size
        />
      </div>
      <!--    账号列表 end   -->
    </div>

    <!--  删除账号/组织 start  -->
    <a-modal
      :visible="isShowDelModal"
      @ok="handleOk"
      @cancel="handleCancel"
      okText="确定"
      cancelText="取消"
      width="400px"
      :mask-closable="false"
      unmountOnClose
      :closable="false"
    >
      <div class="modal-message">
        <div class="del-name">{{ delTitle }}</div>
        <div class="del-tip">{{ delTip }}</div>
      </div>
    </a-modal>
    <!--  删除账号/组织 end  -->

    <!--  批量导入 start  -->
    <a-modal
      :visible="isUpTemplate"
      @ok="handleTemplateOk"
      @cancel="handleTemplateCancel"
      okText="确定"
      cancelText="取消"
      width="488px"
      :mask-closable="false"
      unmountOnClose
      :closable="false"
    >
      <div class="upload-container">
        <div class="modal-title">
          <span class="circle"></span>
          <span>批量导入</span>
        </div>
        <a-upload
          tip="也可以拖拽到此处上传（支持格式xls、xlsx）"
          draggable
          name="file"
          ref="uploadRef"
          :auto-upload="false"
          :limit="1"
          :headers="uploadHeader"
          :action="deptUpExcelUrl"
          :on-before-upload="upLoadFileBefore as any"
          :on-before-remove="upLoadFileRemove as any"
          :file-list="fileList"
          @success="upLoadSuccess"
          @error="upLoadError"
        >
          <template #image>
            <GiSvgIcon name="up-icon" size="16"></GiSvgIcon>
          </template>
        </a-upload>
        <div class="upload-error">{{ uploadErrorTip }}</div>
        <div class="modal-download" @click="getUserImportTemplate">
          <GiSvgIcon name="download-icon" size="16"></GiSvgIcon>
          <span>下载模板导入表格</span>
        </div>
      </div>
    </a-modal>

    <!--  部门设置  start-->
    <a-modal
      :visible="isDeptSet"
      @ok="handleDeptOk"
      @cancel="handleDeptCancel"
      okText="确定"
      cancelText="取消"
      width="660px"
      :mask-closable="false"
      unmountOnClose
      :closable="false"
    >
      <div class="dept-modal">
        <div class="modal-title">
          <span class="circle"></span>
          <span>部门设置</span>
        </div>
        <div class="dept-set-container">
          <div class="dept-set-title">
            <span>部门</span>
            <span>已选中：{{ userDeptList.length }}</span>
          </div>
          <div class="dept-set-body">
            <div class="dept-set-body_dept">
              <a-tree
                :checkable="true"
                :check-strictly="true"
                :data="setDeptTree"
                v-model:checked-keys="checkedDeptIds"
                @check="checkedUserDept as any"
                :fieldNames="treeFieldNames"
              />
            </div>
            <div class="dept-set-body_maindept">
              <div class="maindept-title">
                <span>选择主部门：</span>
                <span>{{ mainDeptName }}</span>
              </div>
              <div class="dept-list">
                <a-radio-group direction="vertical" v-model="mainDeptId" @change="handleMainDeptChange as any">
                  <div class="dept-list-item" v-for="(item, index) in userDeptList" :key="item.deptId">
                    <div class="radio-label">
                      <span>{{ item.deptName }}</span>
                      <a-radio :value="item.deptId"></a-radio>
                    </div>
                    <icon-close @click="delUserDept(index, item)" />
                  </div>
                </a-radio-group>
              </div>
            </div>
          </div>
        </div>
      </div>
    </a-modal>
    <!--  部门设置  end-->

    <!--  新建/编辑账号 start -->
    <a-modal
      :visible="isAddEditAccount"
      @ok="handleAddEditAccountOk"
      @cancel="handleAddEditAccountCancel"
      okText="确定"
      cancelText="取消"
      width="483px"
      :mask-closable="false"
      unmountOnClose
      :closable="false"
    >
      <div class="modal-set-account">
        <div class="modal-title">
          <span class="circle"></span>
          <span>{{ isAddAccount ? "新建账号" : "编辑账号" }}</span>
        </div>
        <a-form :model="accountForm" :rules="accountRules" ref="accountFormRef">
          <a-form-item field="nickName" label="员工名字">
            <a-input placeholder="请输入" v-model.trim="accountForm.nickName" />
          </a-form-item>
          <!--          :disabled="!isAddAccount"-->
          <a-form-item field="mobile" label="手机号码">
            <a-input placeholder="请输入" v-model.trim="accountForm.mobile" />
          </a-form-item>
          <a-form-item field="post" label="角色">
            <a-select :style="{ width: '100%' }" multiple :max-tag-count="2" allow-clear v-model="accountForm.roleIds">
              <a-option v-for="item in roleFormList" :key="item.roleId" :value="item.roleId">{{ item.roleName }} </a-option>
            </a-select>
          </a-form-item>
          <a-form-item field="post" label="工作岗位">
            <a-input placeholder="请输入" v-model.trim="accountForm.post" />
            <!--            default-value="Beijing"-->
            <!--            <a-select :style="{ width: '100%' }"  placeholder="工作岗位">-->
            <!--              <a-option>Beijing</a-option>-->
            <!--            </a-select>-->
          </a-form-item>
          <a-form-item field="post" label="入职日期">
            <a-date-picker v-model="accountForm.entryDate" style="background: #f2f3f5" />
          </a-form-item>
          <a-form-item field="post" label="转正日期">
            <a-date-picker v-model="accountForm.confirmationDate" style="background: #f2f3f5" />
          </a-form-item>
          <a-form-item field="post" label="离职日期">
            <a-date-picker v-model="accountForm.resignDate" style="background: #f2f3f5" />
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!--  新建/编辑账号 end -->

    <!--  新建/编辑组织 start  -->
    <a-modal
      :visible="isAddEditOrg"
      @ok="handleAddEditOrgOk"
      @cancel="handleAddEditOrgCancel"
      okText="确定"
      cancelText="取消"
      width="474px"
      unmount-on-close
      :mask-closable="false"
      :closable="false"
    >
      <div class="modal-set-org">
        <div class="modal-title">
          <span class="circle"></span>
          <span>{{ isAddOrg ? "新建组织" : "编辑组织" }}</span>
        </div>
        <a-form :model="deptForm" :rules="deptRules" ref="deptFormRef">
          <a-form-item field="parentId" label="上级组织">
            <a-tree-select
              :disabled="!isAddOrg"
              :data="deptTreeData"
              v-model.trim="newDeptFormParentId"
              :field-names="treeFieldNames"
              :placeholder="newDeptFormParentId ? '上级组织' : ''"
            ></a-tree-select>
          </a-form-item>
          <a-form-item field="deptName" label="组织名称">
            <a-input placeholder="请输入" v-model.trim="deptForm.deptName" />
          </a-form-item>
          <a-form-item field="post" label="负责人">
            <a-select
              v-model="deptForm.leaderId"
              placeholder="请输入负责人"
              @search="handleSearchHead"
              @change="changeUser as any"
              :loading="isHeadLoading"
              :allow-search="true"
              :filter-option="false"
            >
              <a-option v-for="item in headList" :value="item.userId">{{ item.name }}</a-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>
    <!--  新建/编辑组织 end  -->
  </div>
</template>

<script setup lang="ts">
import _ from "lodash";
import { Message, Modal } from "@arco-design/web-vue";
import type { FileItem, TableRowSelection, FormInstance } from "@arco-design/web-vue";
import type { NodeData, AccountInfo, AccountRoles, DeptFormData } from "./types";
import type { RoleList, UserDeptItem, SearchUser, PersonnelInfo } from "@/apis";
import { useRoute } from "vue-router";
import {
  deptTree,
  deleteDept,
  deptPersonnelList,
  restDefaultPassword,
  getRoleList,
  setPersonnelStatus,
  removeDeptUser,
  batchRemoveDeptUser,
  addPersonnel,
  editPersonnel,
  getPersonnelDetail as personnelDetail,
  addDept,
  deptDetail,
  editDept,
  userDeptDetail,
  saveUserDept,
  userImportTemplate,
  searchPersonnel
} from "@/apis";
import { documentFlow } from "@/utils/downloadFile";
import { getToken } from "@/utils/auth";
import appUrlConfig from "@/config/appUrlconfig.ts";
import * as Regexp from "@/utils/regexp";
import type { CSSProperties } from "vue";

const { proxy } = getCurrentInstance();

const route = useRoute();
/**
 * @desc 部门树
 */
const treeFieldNames = {
  key: "deptId",
  title: "deptName",
  children: "children"
};
const deptTreeData = ref<Array<NodeData>>([]);
const deptName = ref("");
const nowDeptId = ref("");
const getDeptTree = async () => {
  const res = await deptTree(deptName.value);
  deptTreeData.value = res.data;
  deptForm.value.parentId = res.data?.length ? res.data[0].deptId : "";
  nowDeptId.value = deptForm.value.parentId;
};
const handelDeptSearch = _.debounce(getDeptTree, 500);

//处理上级组织
const newDeptFormParentId = computed(() => {
  return deptForm.value.parentId === 0 ? "" : deptForm.value.parentId;
});
/**
 * 删除部门
 */
const handelDel = (nodeData: NodeData) => {
  if (nodeData.children?.length) {
    return Modal.info({
      content: "当前组织下还有用户账号信息，不允许删除，请清空用户账号信息后再操作删除！"
    });
  }
  isDept.value = true;
  delTip.value = "您确定要删除该组织吗？";
  delTitle.value = nodeData.deptName;
  delDataId.value = nodeData.deptId;
  isShowDelModal.value = true;
};
/**
 * 编辑部门
 */
const getDeptDetail = async (deptId: string) => {
  const { data } = await deptDetail(deptId);
  deptForm.value = data ?? {};
  if (data?.leader && data?.leaderId) {
    headList.value = [
      {
        userId: data.leaderId,
        nickName: data.leader,
        name: data.leader,
        deptName: ""
      }
    ];
  }
  isAddEditOrg.value = true;
};
const handelEdit = (nodeData: NodeData) => {
  getDeptDetail(nodeData.deptId);
  isAddEditOrg.value = true;
  isAddOrg.value = false;
};

/**
 * @desc 删除用户
 */
const handelAccount = (data: AccountInfo) => {
  isShowDelModal.value = true;
  isDept.value = false;
  delTitle.value = data.nickName;
  delDataId.value = data.userId;
};

/**
 * @desc 删除账号/组织
 */
const delTip = ref("您确定要删除该账号吗？");
const isShowDelModal = ref(false);
const delTitle = ref("");
const delDataId = ref("");
const isDept = ref(false);
const deleteOrg = async (deptId: string) => {
  await deleteDept(deptId);
  getDeptTree();
  isShowDelModal.value = false;
  Message.success("删除成功！");
};
const deleteDeptUser = async (userId: string) => {
  await removeDeptUser(userId);
  Message.success("删除成功！");
  getAccountList();
  isShowDelModal.value = false;
};
const handleOk = () => {
  isDept.value ? deleteOrg(delDataId.value) : deleteDeptUser(delDataId.value);
};
const handleCancel = () => {
  isShowDelModal.value = false;
};

/**
 * @desc 账号
 */
const listParams = ref({
  deptId: "",
  name: route.query.name as string,
  current: 1,
  size: 15
});
const accountList = ref<AccountInfo[]>([]);
const paginationTotal = ref(0);
//  todo:待优化
const userRole = computed(() => {
  return (roles: AccountRoles[]) => {
    const roleList: string[] = roles?.map(item => {
      return item.roleName;
    });
    return roleList?.join(",");
  };
});
const rowSelection = {
  type: "checkbox",
  showCheckedAll: true
} as TableRowSelection;
const selectedUserKeys = ref<string[]>([]);
const getAccountList = async () => {
  const res = await deptPersonnelList(listParams.value);
  accountList.value = res.data.list;
  paginationTotal.value = res.data.total;
};
/**
 * 选中树节点
 * @param nodekey
 */
const selectedOrgKeys = ref([]);
const handelTreeList = (nodekey: any) => {
  const nodeId = nodekey?.length ? nodekey[0] : "";
  if (nodeId === nowDeptId.value) {
    selectedOrgKeys.value = [];
    listParams.value = {
      deptId: "",
      name: route.query.name as string,
      current: 1,
      size: 15
    };
    nowDeptId.value = "";
    getAccountList();
    return;
  }
  listParams.value.deptId = nodeId;
  deptForm.value.parentId = nodeId;
  nowDeptId.value = nodeId;
  getAccountList();
};
const handleChangePagination = (val: number) => {
  listParams.value.current = val;
  getAccountList();
};
const handleChangeSizePagination = (val: number) => {
  listParams.value.size = val;
  getAccountList();
};
const handelAccountSearch = _.debounce(getAccountList, 500);
const handelAccountStatus = (record: AccountInfo) => {
  record.status = !record.status;
  record.loading = true;
  setPersonnelStatus(record.status, record.userId)
    .then(() => {
      Message.success("修改成功！");
      record.loading = false;
    })
    .catch(() => {
      record.status = !record.status;
      record.loading = false;
    });
};

const handelBatchDel = () => {
  if (!selectedUserKeys.value.length) {
    return Message.warning("请选择要删除的账号！");
  }
  Modal.info({
    title: "批量删除账号",
    content: "确定删除所选账号吗？",
    onOk: () => {
      batchRemoveDeptUser(selectedUserKeys.value).then((res: any) => {
        if (res.code === 20003) {
          Modal.error({
            title: "提示",
            content: res.msg
          });
        }
        if (res.code === 20002) {
          Message.success(res.msg);
        }
        selectedUserKeys.value = [];
        getAccountList();
      });
    },
    onCancel: () => {
      console.log("取消");
    }
  });
};

/**
 * @desc 导入
 */
const getUserImportTemplate = async () => {
  const res = await userImportTemplate();
  documentFlow(res, "导入模板", "xlsx");
};
const uploadErrorTip = ref("");
const deptUpExcelUrl = ref(appUrlConfig.deptUpExcelUrl);
const uploadHeader = ref({
  Authorization: `Bearer ${getToken()}`
});
const fileList = ref<FileItem[]>([]);

const getSuffix = (fileName: string) => {
  return fileName.slice(fileName.lastIndexOf(".") + 1);
};
const upLoadFileBefore = (fileItem: FileItem) => {
  const suffix = ["xls", "xlsx"];
  if (fileItem.name && !suffix.includes(getSuffix(fileItem.name))) {
    Message.error("请上传xls、xlsx文件！");
    return false;
  }
  return true;
};
const upLoadFileRemove = () => {
  uploadErrorTip.value = "";
  fileList.value = [];
};
const upLoadSuccess = (fileItem: FileItem) => {
  const { code, msg } = fileItem.response;
  if (code !== 200) {
    uploadErrorTip.value = msg;
    return Message.error(msg);
  }
  handleTemplateCancel();
  getAccountList();
  Message.success("导入成功！");
};
const upLoadError = () => {
  Message.error("导入失败！");
};

const isUpTemplate = ref(false);
const handleUpTemplate = () => {
  isUpTemplate.value = true;
};
/**
 * 手动上传
 */
const uploadRef = ref();
const handleTemplateOk = async () => {
  await nextTick();
  uploadRef.value.submit();
  // handleTemplateCancel()
};
const handleTemplateCancel = () => {
  isUpTemplate.value = false;
  uploadErrorTip.value = "";
};

/**
 * @desc 重置密码
 */
const handelResetPassword = async (data: AccountInfo) => {
  await restDefaultPassword(data.userId);
  Message.success("重置密码成功！");
};

/**
 * @desc 部门设置
 */
const isDeptSet = ref(false);
const checkedDeptIds = ref<string[]>([]);
const setDeptTree = ref<Array<NodeData>>([]);
const userDeptList = ref<Array<UserDeptItem>>([]);
const mainDeptName = ref("--");
const mainDeptId = ref("");
const userId = ref("");
const getUserDeptDetail = async (userId: string) => {
  const res = await userDeptDetail(userId);
  isDeptSet.value = true;
  setDeptTree.value = res.data?.deptTree || [];
  userDeptList.value = res.data?.deptList || [];
  checkedDeptIds.value = res.data?.deptList.map((item: UserDeptItem) => {
    if (item.isMain) {
      mainDeptName.value = item.deptName;
      mainDeptId.value = item.deptId;
    }
    return item.deptId;
  });
};
const checkedUserDept = (keys: string[], data: any) => {
  if (!keys.includes(mainDeptId.value)) {
    mainDeptName.value = "--";
    mainDeptId.value = "";
  }
  checkedDeptIds.value = keys;
  userDeptList.value = data.checkedNodes;
};
const delUserDept = (index: number, item: UserDeptItem) => {
  if (item.deptId === mainDeptId.value) {
    mainDeptName.value = "--";
    mainDeptId.value = "";
  }
  checkedDeptIds.value.splice(index, 1);
  userDeptList.value.splice(index, 1);
};
const handleMainDeptChange = (key: string) => {
  userDeptList.value?.some(item => {
    if (item.deptId === key) {
      mainDeptName.value = item.deptName;
      mainDeptId.value = item.deptId;
      return true;
    }
  });
};
const handelDeptSet = (record: any) => {
  userId.value = record.userId;
  getUserDeptDetail(record.userId);
};
const handleDeptOk = async () => {
  const postData = {
    deptIds: checkedDeptIds.value,
    mainDeptId: mainDeptId.value
  };
  await saveUserDept(userId.value, postData);
  Message.success("设置成功！");
  handleDeptCancel();
};
const handleDeptCancel = () => {
  isDeptSet.value = false;
  mainDeptName.value = "--";
  mainDeptId.value = "";
  setDeptTree.value = [];
  userDeptList.value = [];
  checkedDeptIds.value = [];
};

/**
 * 新建/编辑组织
 */
const isAddEditOrg = ref(false);
// 默认新增
const isAddOrg = ref(true);
const deptForm = ref<DeptFormData>({
  parentId: "",
  deptName: "",
  leader: "",
  leaderId: ""
});
const deptRules: FormInstance["rules"] = {
  parentId: [{ required: true, message: "上级部门不能为空" }],
  deptName: [
    { required: true, message: "请输入部门名称" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符" }
  ]
};
// 获取负责人列表
const isHeadLoading = ref(false);
const headList = ref<Array<SearchUser>>([]);
// 搜索人
const getSearchPersonnel = async (val: string) => {
  isHeadLoading.value = true;
  const defaultData = { nickName: deptForm.value.leader, userId: deptForm.value.leaderId, name: deptForm.value.leader };
  const { data } = await searchPersonnel({ name: val });
  const list: SearchUser[] = data || [];
  const isHas = list.some((item: SearchUser) => item.userId === deptForm.value.leaderId);
  const searchData = list.map((item: SearchUser) => {
    return {
      ...item,
      name: item.deptName ? `${item.nickName}-${item.deptName}` : item.nickName
    };
  });
  headList.value = isHas ? list : ([defaultData, ...searchData] as any);
  isHeadLoading.value = false;
};
const handleSearchHead = _.debounce(getSearchPersonnel, 500);
const changeUser = (val: string) => {
  deptForm.value.leaderId = val;
  deptForm.value.leader = headList.value.find((item: SearchUser) => item.userId === val)?.nickName || "";
};
const handleOpenAddEditOrg = () => {
  isAddEditOrg.value = true;
  isAddOrg.value = true;
  deptForm.value.parentId = deptForm.value.parentId || nowDeptId.value;
};
const handleAddEditOrg = async () => {
  const valid = await proxy.$refs.deptFormRef?.validate();
  if (valid) return;
  if (isAddOrg.value) {
    await addDept(deptForm.value);
    getDeptTree();
    isAddEditOrg.value = false;
    resetOrgForm();
    Message.success("新建组织成功！");
    return;
  }
  await editDept(deptForm.value, deptForm.value?.deptId);
  await getDeptTree();
  isAddEditOrg.value = false;
  resetOrgForm();
  Message.success("组织修改成功！");
};
const handleAddEditOrgOk = _.debounce(handleAddEditOrg, 500);
const handleAddEditOrgCancel = () => {
  isAddEditOrg.value = false;
  resetOrgForm();
};
const resetOrgForm = () => {
  deptForm.value = {
    parentId: "",
    deptName: "",
    leader: "",
    leaderId: ""
  };
  headList.value = [];
};

/**
 * 新建/编辑账号
 */
const isAddEditAccount = ref(false);
const isAddAccount = ref(true);
const accountForm = ref<PersonnelInfo>({
  roleIds: [],
  nickName: "",
  mobile: "",
  post: "",
  entryDate: "",
  confirmationDate: "",
  resignDate: ""
});
const accountRules: FormInstance["rules"] = {
  nickName: [
    { required: true, message: "请输入员工名字" },
    { min: 2, max: 10, message: "长度在 2 到 10 个字符" }
  ],
  mobile: [
    { required: true, message: "请输入手机号" },
    { match: Regexp.Phone, message: "请输入正确的手机号" }
  ]
};
const roleFormList = ref<RoleList[]>([]);
// 角色列表
const getRoleListData = async () => {
  const res = await getRoleList();
  roleFormList.value = res.data || [];
};
// 人员详情
const getPersonnelDetail = async (userId: string) => {
  const res = await personnelDetail(userId);
  res.data.roleIds = res.data.roles?.map((item: any) => item.roleId);
  accountForm.value = res.data;
};
const handelEditAccount = (record: any) => {
  getRoleListData();
  getPersonnelDetail(record.userId);
  isAddEditAccount.value = true;
  isAddAccount.value = false;
};
const handelAddAccount = () => {
  isAddEditAccount.value = true;
  isAddAccount.value = true;
  getRoleListData();
};
const handleAddEditAccount = async () => {
  const valid = await proxy.$refs.accountFormRef?.validate();
  if (valid) return;
  const postData = {
    ...accountForm.value
  };
  if (isAddAccount.value) {
    addPersonnel(postData, listParams.value.deptId)
      .then(() => {
        Message.success("添加成功！");
        getAccountList();
        isAddEditAccount.value = false;
        resetAccountForm();
      })
      .catch(() => {});
    return;
  }
  editPersonnel(postData, postData.userId)
    .then(() => {
      Message.success("修改成功！");
      getAccountList();
      isAddEditAccount.value = false;
      resetAccountForm();
    })
    .catch(() => {});
};
const handleAddEditAccountOk = _.debounce(handleAddEditAccount, 500);
const handleAddEditAccountCancel = () => {
  isAddEditAccount.value = false;
  resetAccountForm();
};
const resetAccountForm = () => {
  accountForm.value = {
    roleIds: [],
    nickName: "",
    mobile: "",
    post: ""
  };
};

getDeptTree();
getAccountList();
</script>

<style scoped lang="scss">
@import "index";

.user-list_btn {
  width: auto;
  height: 20px;
  padding: 0;

  & + .user-list_btn {
    margin-left: 13px;
  }
}

:deep(.arco-tree-node) {
  padding-right: 8px;

  &:hover {
    background-color: #d9e8ff;
  }
}

:deep(.arco-tree-node-selected) {
  background-color: #d9e8ff;
}

:deep(.arco-tree-node-title) {
  &:hover {
    background-color: #d9e8ff;
  }
}

:deep(.arco-table-header) th {
  background-color: #f2f6fc !important;
}

:deep(.arco-table-body) tr:nth-child(2n) td {
  background-color: #f5f7fa !important;
}
</style>
